package pcf8591

import (
	"periph.io/x/conn/v3"
	"periph.io/x/conn/v3/i2c"
)

// Channel 模拟信号输入
type Channel uint8

// AIN0～AIN3 模拟信号输入端
const (
	AIO0 Channel = 0
	AIO1 Channel = 1
	AIO2 Channel = 2
	AIO3 Channel = 3
)

// Dev is a handle to an initialized PCF8591 device.
type Dev struct {
	d    conn.Conn
	name string
}

// NewI2C returns an object that communicates over I²C to PCF8591
func NewI2C(b i2c.Bus, addr uint16) (*Dev, error) {
	d := &Dev{d: &i2c.Dev{Bus: b, Addr: addr}}
	return d, nil
}

// Read 读取结果
func (d *Dev) Read(channel Channel) (result byte) {
	tmp := make([]byte, 1)
	var err error
	switch channel {
	case AIO0:
		err = d.d.Tx([]byte{0x40}, tmp)
	case AIO1:
		err = d.d.Tx([]byte{0x41}, tmp)
	case AIO2:
		err = d.d.Tx([]byte{0x42}, tmp)
	case AIO3:
		err = d.d.Tx([]byte{0x43}, tmp)
	}
	if err != nil {
		println("err", err.Error())
		return
	}
	//println(tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], tmp[5], tmp[6], tmp[7], tmp[8], tmp[9])
	result = tmp[0]
	return
}

// Write 写入数据
func (d *Dev) Write(val byte) {
	d.d.Tx([]byte{0x40, val}, nil)
}
